﻿<%@ WebHandler Language="C#" Class="ZSDealFaultBillHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Collections.Generic;
using System.Collections;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;

public class ZSDealFaultBillHandler : IHttpHandler,IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSDealFaultBillIbusiness m_DealFaultBill = uMESBusinessFactory.instance.GetuLMSdealFaultBillObject();
    string fileBasePath = System.Configuration.ConfigurationManager.AppSettings["ImportPath"].ToString();//导入临时路径
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "GetOrderData"://查询订单信息
                    GetOrderData(context);
                    break;
                case"GetDealFaultBillData"://查询排故单信息
                    GetDealFaultBillData(context);
                    break;
                case "CreateDealFaultBill"://创建排故单
                    CreateDealFaultBill(context);
                    break;
                case"DeleteDealFaultBill"://删除排故单
                    DeleteDealFaultBill(context);
                    break;       
                case "GetDealFaultBillSheet": //查询排故单附页信息
                    GetDealFaultBillSheet(context);
                    break;
                case "ImportDealFaultBillSheet": //导入排故单附页信息
                    ImportDealFaultBillSheet(context);
                    break;
                case "GetDataDealFaultBillVendor": //排故返件供应商
                    GetDataDealFaultBillVendor(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            var result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.ContentType = "text/html";
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }
    /// <summary>
    /// 查询订单信息
    /// </summary>
    /// <param name="context"></param>
    private void GetOrderData(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string,string>>(context.Request["data"].ToString());
        string pageSize = context.Request["pageSize"].ToString();
        string pageNumber = context.Request["pageNumber"].ToString();
        var para=new Dictionary<string,string>();
        para.Add("PageSize", pageSize);
        para.Add("CurrentPageIndex", pageNumber);
        para.Add("IsReturn", "0");
        para.Add("FactoryID", m_UserInfo.FactoryID);
        if (!string.IsNullOrWhiteSpace(argPara["Machine"]))
        {
            para.Add("Machine", argPara["Machine"]);
        }
        if (!string.IsNullOrWhiteSpace(argPara["MfgOrderName"]))
        {
            para.Add("MfgOrderName", argPara["MfgOrderName"]);
        }
        if (!argPara["Status"].Equals("全部"))
        {
            para.Add("Status", argPara["Status"]);
        }
        
        var result = m_DealFaultBill.GetPGMfgorderinfo(para);
        context.Response.Write(JsonConvert.SerializeObject(result)); 
    }
    /// <summary>
    /// 查询排故单信息
    /// </summary>
    /// <param name="context"></param>
    private void GetDealFaultBillData(HttpContext context) 
    {
        var mfgid = context.Request["mfgid"].ToString();
        var result = m_DealFaultBill.GetPGDbyMfgId(mfgid, "0");
        context.Response.Write(JsonConvert.SerializeObject(result)); 
    }
    /// <summary>
    /// 创建排故单
    /// </summary>
    /// <param name="context"></param>
    private void CreateDealFaultBill(HttpContext context) 
    {
        var argPara = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["data"].ToString());
        var result = new uMESProcessResult();
        context.Session["PopupData"] = argPara;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 删除排故单
    /// </summary>
    /// <param name="context"></param>
    private void DeleteDealFaultBill(HttpContext context) 
    {
        var result = new uMESProcessResult();
        var dfname=context.Request["dfname"].ToString();
        result.Result= m_DealFaultBill.DeleteDealFaultBill(dfname);
        result.Message = result.Result ? "删除成功" : "删除失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    /// <summary>
    /// 查询排故单附页信息
    /// </summary>
    /// <param name="context"></param>
    private void GetDealFaultBillSheet(HttpContext context)
    {
        var dealFaultBillID = context.Request["dealFaultBillId"].ToString();
        var result = new uMESProcessResult();
        var selectSQL = @"select d.DealFaultBillname,ds.* from DealFaultBillSheet ds left join DealFaultBill d on d.dealFaultBillNAME=ds.dealFaultBillNAME where d.dealFaultBillID='" + dealFaultBillID + "'order by ds.SHEETNO ASC";
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(selectSQL);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 导入排故单附页信息
    /// </summary>
    /// <param name="context"></param>
    private void ImportDealFaultBillSheet(HttpContext context)
    {
        var dealFaultBillNAME = context.Request["dealFaultBillName"].ToString();
        string fpath = string.Empty;
        try
        {
            var files = context.Request.Files;
            if (files.Count == 0)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = "未上传文件！", Result = false }));
                return;
            }
            if (!System.IO.Directory.Exists(context.Server.MapPath(fileBasePath)))
            {
                System.IO.Directory.CreateDirectory(context.Server.MapPath(fileBasePath));
            }
            var file = files.Count > 1 ? files[files.Count - 1] : files[0];
            string IsXls = System.IO.Path.GetExtension(file.FileName);
            string fileName = System.IO.Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now.ToString("yyyyMMddHHmmssffff") + IsXls;
            fpath = context.Server.MapPath(fileBasePath + fileName);
            file.SaveAs(fpath);//保存文件，处理完成后删除
            NPOI.SS.UserModel.IWorkbook Workbook = uLMS_CommonFunction.GetWorkbookObj(fpath);
            DataTable dt = uLMS_CommonFunction.ExcelImportToDataTable(Workbook);
            uLMS_CommonFunction.DeleteFile(fpath);
            uMESProcessResult result = SaveDealFaultBillSheet(dt, dealFaultBillNAME);
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
        catch (Exception ex)
        {
            uLMS_CommonFunction.DeleteFile(fpath);//报错，则删除上传的文件
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Message = ex.Message, Result = false }));
        }
    }

    private uMESProcessResult SaveDealFaultBillSheet(DataTable dt, string dealFaultBillNAME) 
    {   
        var result=new uMESProcessResult();
        var insertSQL = @"insert into DealFaultBillSheet(DEALFAULTBILLSHEETID,dealFaultBillNAME,SHEETNO,PRODUCTNAME,PRODUCTDESC,BATCHNO,BATCHQTY,NOTE)
                            values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}')";
        var updateSQL = @"update DealFaultBillSheet set  SHEETNO='{0}',PRODUCTNAME='{1}',PRODUCTDESC='{2}',BATCHNO='{3}',BATCHQTY='{4}',NOTE='{5}' where DEALFAULTBILLSHEETID='{6}'";
        var arrSQL = new ArrayList();
        foreach(DataRow row in dt.Rows)
        {
            DataTable Edt = DatabaseHelper.Query_ReturnDatTable(string.Format("select * from DealFaultBillSheet where dealFaultBillNAME='{0}' and PRODUCTNAME='{1}' and BATCHNO='{2}'", dealFaultBillNAME, row["零件号"], row["批次号"]));
            if (Edt.Rows.Count > 0)
            {
                arrSQL.Add(string.Format(updateSQL, row["序号"], row["零件号"], row["零件名称"], row["批次号"], row["批次数量"], row["备注"], Edt.Rows[0]["DEALFAULTBILLSHEETID"]));
            }
            else
            {
                arrSQL.Add(string.Format(insertSQL, Guid.NewGuid().ToString(), dealFaultBillNAME, row["序号"], row["零件号"], row["零件名称"], row["批次号"], row["批次数量"], row["备注"]));
            }
        }
        result.Result = DatabaseHelper.ExecuteSqlListTran(arrSQL);
        result.Message = result.Result ? "上传成功" : "上传失败";
        return result;
    }

    private void GetDataDealFaultBillVendor(HttpContext context) 
    {
        DataTable dt_vendor = DatabaseHelper.Query_ReturnDatTable(@"SELECT item.customobjectitemsid,item.customobjectitemsname,item.customobjectitemsdesc FROM customobject cus 
                    LEFT JOIN customobjectitems item ON item.customobjectid =cus.customobjectid
                    WHERE cus.customobjectname ='排故返件供应商'
                    ORDER BY item.sequence
                    ");
        DataRow newRow = dt_vendor.NewRow();
        newRow["customobjectitemsid"] = "";
        newRow["customobjectitemsname"] = "";
        newRow["customobjectitemsdesc"] = "";
        dt_vendor.Rows.InsertAt(newRow,0);
        context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result=true,DBTable=dt_vendor}));
    }
}